package com.mdp.dev.ctrl;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.mdp.core.SpringContextUtils;
import com.mdp.core.entity.Result;
import com.mdp.core.utils.BaseUtils;
import com.mdp.core.utils.ObjectTools;
import com.mdp.dev.dao.CodeGenDao;
import com.mdp.dev.entity.FieldInfo;
import com.mdp.dev.service.CodeGenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023-9-22
 */
@RestController
@RequestMapping(value="/**/dev/db")
@Api(tags={"查询数据库的表信息"})
public class DbController {
	
	static Logger logger =LoggerFactory.getLogger(DbController.class);


	DynamicRoutingDataSource dataSourceService;

	/**生成代码*/
	@Autowired
	CodeGenDao codeGenDao;

	@ApiOperation( value = "查询表的列信息",notes=" ")
 	@ApiResponses({
		@ApiResponse(code = 200,response=FieldInfo.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")
	})
	@RequestMapping(value="/table/column/list",method=RequestMethod.GET)
	public Result tableInfo(@ApiIgnore @RequestParam Map<String,Object> params){
		CodeGenService codeGenService=new CodeGenService();

			String owner= (String) params.get("owner");
			String tableName= (String) params.get("tableName");
			if(ObjectTools.isEmpty(owner)){
				return Result.error("owner-required","数据库用户名、或者模式名不能为空");
			}
			if(ObjectTools.isEmpty(owner)){
				return Result.error("tableName-required","表名不能为空");
			}
			List<FieldInfo> datas=codeGenDao.getColumnsInfo(owner,tableName);
			return Result.ok().setData(datas).setTotal(datas!=null?datas.size():0);
	}



	@ApiOperation( value = "查询数据源列表",notes=" ")
	@ApiResponses({
			@ApiResponse(code = 200,response=FieldInfo.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")
	})
	@RequestMapping(value="/dataSource/list",method=RequestMethod.GET)
	public Result dsList(@ApiIgnore @RequestParam Map<String,Object> params){
		if(dataSourceService==null){
			dataSourceService= SpringContextUtils.getBean(DynamicRoutingDataSource.class);
		}
		Map<String, DataSource> maps=dataSourceService.getDataSources();
		return Result.ok().setData(maps.keySet().stream().map(k-> BaseUtils.map("id",k,"name",k)).collect(Collectors.toList()));
	}


}
